package viperconf

import (
	"fmt"
	"io"
	"os"

	"gitee.com/korbenzhang/gox/xconfig"
	"github.com/spf13/viper"
)

// ViperConf implements config.Config
type ViperConf struct {
	Viper *viper.Viper
}

// make sure implements xconfig.Config
var _ xconfig.Config = &ViperConf{}

// New Create new ViperConf instanse.
func New() *ViperConf {
  impl:= &ViperConf{
    Viper: viper.New(),
  }
	impl.Viper.SetConfigType("yaml")
  return impl
}

// MergeConfig .
// Read text from local file, or etcd.
func (c *ViperConf) Merge(r io.Reader) error {
  return c.Viper.MergeConfig(r)
}

// GetString .
func (c *ViperConf) GetString(key string, dv ...any) string {
	if c.Viper.IsSet(key) {
		v := fmt.Sprint(c.Viper.Get(key))
		return os.ExpandEnv(v)
	}
  if len(dv)!=0{
    return fmt.Sprint(dv[0])
  }
	return ""
}

// Set put value to config.
func (c *ViperConf) Put(key string, value any) error {
	c.Viper.Set(key, value)
  return nil
}

// Unmarshal .
func (c *ViperConf) Unmarshal(key string, ptr any) error{
  if key == "" {
    return c.Viper.Unmarshal(ptr)
  }
  return c.Viper.UnmarshalKey(key,ptr)
}
